/**
 * 登录控制器
 */
angular
.module('myApp')
.controller('loginController', function($scope, $location, tokenManager, userManager) {

  $scope.$watch('isSubmitted', function() {
    $scope.isSubmitted
      ? $.showLoading('登录中...')
      : $.hideLoading();
  });

  var getFirstError = function(errors) {
    for(var key in errors) break;
    return errors[key];
  }

  $scope.processSubmit = function() {

    if (angular.isUndefined($scope.mobile)) {
      $scope.errorMessage = '请填写手机号！';
      return false;
    }

    if (angular.isUndefined($scope.password)) {
      $scope.errorMessage = '请填写登录密码！';
      return false;
    }

    $scope.isSubmitted  = true;
    $scope.errorMessage = false;

    userManager.login($scope.mobile, $scope.password)
      .then(function(data) {
        tokenManager.setToken(data.access_token, data.expire_in);
        $location.path((data.openid == '') ? '/wechat' : '/');
      }, function(data) {
        $scope.errorMessage = angular.isDefined(data.errors)
          ? getFirstError(data.errors)
          : data.msg;
      })
      .finally(function() {
        $scope.isSubmitted = false;
      });
  }
});
